package com.example.service.Impl;

import com.example.mapper.ActivityMapper;
import com.example.pojo.Activity;
import com.example.utils.Result;
import com.example.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;


    //添加活动
    @Override
    public void add(Activity activity) {
        activity.setCreatedTime(LocalDateTime.now());
        activityMapper.InsertActivity(activity);
    }

    //根据发布状态查询活动
    @Override
    public List<Activity> query(String status) {
        List<Activity> list = activityMapper.queryActivityByStatus(status);
        return list;
    }
    //编辑活动
    @Override
    public void update(Activity activity) {
        activity.setCreatedTime(LocalDateTime.now());
        activityMapper.updateActivity(activity);
    }

    //发布活动
    @Transactional
    @Override
    public Result publishActivity(Integer id) {
        Activity activity = activityMapper.queryActivityById(id);
        String status = activity.getStatus();
        if(ObjectUtils.isEmpty(activity)){
            //检查该活动是否存在
            log.error("查询不到活动{}，活动不存在："+id);
            return Result.error("活动不存在");
        }
        else if(status.equals("1")){
            //检查该活动是否发布
            log.error("活动已发布");
            return Result.error("活动已发布");
        }
        else if(status.equals("2")){
            log.error("活动已归档");
            return Result.error("活动已归档");
        }
        else if(status.equals("0")){
            //更新发布状态
            activity.setStatus("1");
            //发布时间
            activity.setStartTime(LocalDateTime.now());
            //更新活动
            activityMapper.updateActivity(activity);
            log.info("活动成功发布");
            return Result.success();
        }
        return Result.error("活动已删除");
    }

    //根据id查询活动
    @Override
    public Activity query(Integer id) {
        Activity activity = activityMapper.queryActivityById(id);
        return activity;
    }
}
